package com.heima.admin.interceptor;

import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到请求头中的userId
        String userId = request.getHeader("userId");
        //如果不为空,放入threadLocal
        if (StringUtils.isNotBlank(userId)){
            ApUserThreadLocalUtil.set(Integer.parseInt(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //用完清理线程内容
        ApUserThreadLocalUtil.clear();
    }
}
